﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using Microsoft.Win32;

namespace GenerateMarkdown
{

    public partial class Form1 : Form
    {

        private string fileMDlinks = string.Empty;//markdown链接
        private string userName;
        private string userEmail;
        private string token;
        private string url;
        private string imgurl;
        private string project;
        private string imgapi;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //初始居中显示
                int x = (System.Windows.Forms.SystemInformation.WorkingArea.Width - this.Size.Width) / 2;
                int y = (System.Windows.Forms.SystemInformation.WorkingArea.Height - this.Size.Height) / 2;
                this.StartPosition = FormStartPosition.Manual; //窗体的位置由Location属性决定
                this.Location = (Point)new Size(x, y);         //窗体的起始位置为(x,y)
                                                               //注册
                button1_Click(sender, e);

                GetSetJson();
                ShortcutCreator.CreateShortcut(System.Windows.Forms.Application.StartupPath, "GenerateMarkdownGitHub.exe.lnk", System.Windows.Forms.Application.StartupPath + @"\GenerateMarkdownGitHub.exe", null, null); //创建快捷方式
                CreateStart();


            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }


        }

        [DllImport("kernel32")]
        public static extern int GetModuleFileName(int hModule, string lpFileName, int nSize);
        /// <summary>
        /// 读配置
        /// </summary>
        private void GetSetJson()
        {
            try
            {


                string strPath = System.Windows.Forms.Application.StartupPath;

                StreamReader r = new StreamReader(strPath + @"\appsettings.json");
                string json = r.ReadToEnd();
                var setList = JsonConvert.DeserializeObject<Dictionary<string,object>>(json);
                if (setList["imgapi"].ToString() == "github")
                {
                    imgapi = "github";
                    var setList1 = JsonConvert.DeserializeObject<Dictionary<string, string>>(setList[imgapi].ToString());
                    userName = setList1["name"];
                    userEmail = setList1["email"];
                    token = setList1["token"];
                    project = setList1["project"];
                    url = @"https://api.github.com/repos/" + @project + @"/contents/img/";
                    imgurl = @"https://raw.githubusercontent.com/" + @project + @"/master/img/";
                }
                if (setList["imgapi"].ToString() == "gitee")
                {
                    imgapi = "gitee";
                    var setList1 = JsonConvert.DeserializeObject<Dictionary<string, string>>(setList[imgapi].ToString());
                    token = setList1["token"];
                    project = setList1["project"];
                    url = @"https://gitee.com/api/v5/repos/" + @project + @"/contents/img/";
                    imgurl = @"https://gitee.com/" + @project + @"/raw/master/img/";
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        //注册
        private void button1_Click(object sender, EventArgs e)
        {
            //注册热键Ctrl+B，Id号为100。HotKey.KeyModifiers.Ctrl也可以直接使用数字2来表示。  
            HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Alt, Keys.V);
            labIsRegister.Text = "(已注册)";
        }
        //注销
        private void button2_Click(object sender, EventArgs e)
        {
            //注销Id号为100的热键设定  
            HotKey.UnregisterHotKey(Handle, 100);
            labIsRegister.Text = "(未注册)";
        }

        /// <summary>
        /// 监视Windows消息  
        /// 重载WndProc方法，用于实现热键响应 
        /// </summary>
        /// <param name="m"></param>

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键  
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:     //按下的是alt  V
                            try
                            {
                                //记录图片地址
                                var PngName = (DateTime.Now + ".png").Replace(" ", "").Replace("/", "").Replace(":", "");
                                fileMDlinks = @imgurl + PngName;
                                fileMDlinks = "![](" + fileMDlinks + ")" + "\n";


                                if (Clipboard.GetFileDropList().Count > 0) //复制图片
                                {
                                    string[] files = new string[Clipboard.GetFileDropList().Count];
                                    Clipboard.GetFileDropList().CopyTo(files, 0);
                                    Clipboard.Clear();

                                    UploadFiles(files[0], PngName);

                                }
                                else if (Clipboard.GetImage() != null) //截图
                                {
                                    UploadCacheFileStr(Clipboard.GetImage(),PngName);
                                }
                                else
                                {
                                    throw new Exception("请选择文件或者截图，才能生成Markdown链接！");
                                }


                                Clipboard.SetDataObject(fileMDlinks);
                                System.Windows.Forms.SendKeys.Send("%");
                                System.Windows.Forms.SendKeys.Send("^v");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }

                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }
        /// <summary>
        /// 文件对象上传
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private bool UploadFiles(string filePath,string PngName)
        {
            try
            {
                string strPic = Base64File.GetBase64(filePath);


                UploadGit(strPic, PngName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return true;

        }
        /// <summary>
        /// 缓存文件字符流上传
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private bool UploadCacheFileStr(Image image,string PngName)
        {
            try
            {
                string strPic = Base64File.GetBase64(image);


                UploadGit(strPic, PngName);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return true;
        }
        /// <summary>
        /// 调用github上传方法
        /// </summary>
        /// <param name="strPic">图片base64</param>
        /// <param name="PngName">图片名字</param>
        private void UploadGit(string strPic,string PngName)
        {
            try
            {
                if (imgapi == "github")
                {
                    var jsonObject1 = new
                    {

                        name = userName, //github用户名
                        email = userEmail //github账号绑定邮箱
                    };


                    var jsonObject = new
                    {
                        message = "commit from markdown", //提交备注
                        content = strPic, //图片base64
                        committer = jsonObject1
                    };
                    string jsonStr = JsonConvert.SerializeObject(jsonObject); //序列化为JSON，作为http请求的data参数


                    Http.GitHubPut(token, userName, @url + PngName, jsonStr);
                }
                if (imgapi == "gitee")
                {



                    var jsonObject = new
                    {
                        message = "commit from markdown", //提交备注
                        content = strPic, //图片base64
                        access_token = token
                    };
                    string jsonStr = JsonConvert.SerializeObject(jsonObject); //序列化为JSON，作为http请求的data参数


                    Http.GiteePost( @url + PngName, jsonStr);
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }


        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //取消关闭窗口
            e.Cancel = true;
            //最小化主窗口
            //this.WindowState = FormWindowState.Minimized;
            //不在系统任务栏显示主窗口图标
            // this.ShowInTaskbar = false;备注：不能加这句；此行会取消热键句柄，导致热键失效
            this.Hide();
            //提示气泡
            //notifyIcon1.ShowBalloonTip(2000, "最小化到托盘", "程序已经缩小到托盘，单击打开程序。", ToolTipIcon.Info);
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {

                //还原窗体
                this.WindowState = FormWindowState.Normal;
                //系统任务栏显示图标
                //this.ShowInTaskbar = true;
                this.Show();
         
                //激活窗体并获取焦点
                this.Activate();
            }
            
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
        
            //还原窗体
            this.WindowState = FormWindowState.Normal;
            //系统任务栏显示图标
            //this.ShowInTaskbar = true;
            this.Show();
         
            //激活窗体并获取焦点
            this.Activate();
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            button2_Click(sender, e);
            this.Dispose();
            this.Close();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            CreateStart();
        }

        /// <summary>
        /// 设置开机启动
        /// </summary>
        private void CreateStart()
        {
            try
            {

                //设置开机自启动  
                if (checkBox1.Checked == true)
                {

                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.SetValue(System.Reflection.Assembly.GetExecutingAssembly().FullName, path);
                    rk2.Close();
                    rk.Close();


                }


                else
                {

                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.DeleteValue(System.Reflection.Assembly.GetExecutingAssembly().FullName, false);
                    rk2.Close();
                    rk.Close();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            //隐藏任务栏区图标
            this.Hide();
            //图标显示在托盘区
            notifyIcon1.Visible = true;
        }
    }
}
